<template>
  <page-header-wrapper @back="() => $router.go(-1)">
    <div class="permissionContent">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="48">
          <a-col :md="12" :sm="24">
            <a-form-model-item ref="name" label="角色名称" prop="name">
              <a-input v-model="form.name" :maxLength="10" :disabled="!isEdit" @change="handleDesChange" @blur="handleNameChange" />
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-model-item label="描述" prop="description">
              <a-input v-model="form.description" :maxLength="100" @change="handleDesChange" :disabled="!isEdit" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="48">
          <a-col :md="12" :sm="24">
            <!-- <a-form-model-item prop="repeat" label="复用权限">
              <div style="display:flex;align-items:center;height:40px">
                <a-radio-group v-model="form.copyVisible" @change="handleCopyChange" >
                  <a-radio :value="0"> 否 </a-radio>
                  <a-radio :value="1"> 是 </a-radio>
                </a-radio-group>
                <a-select v-if="form.copyVisible == 1" v-model="roleId" style="width:200px" allowClear @change="handleUserRoleChange" >
                  <a-select-option v-for="item in userRoleList" :key="item.roleId" :value="item.roleId">{{ item.roleName }}</a-select-option>
                </a-select>
              </div>
            </a-form-model-item> -->
            <a-form-model-item label="角色标识" prop="code">
              <a-radio-group name="radioGroup" v-model="form.code" @change="handleCodeChange" disabled>
                <a-radio v-for="item in roleCodeList" :key="item" :value="item" style="height:30px" :disabled="item == 'Subjects'" >
                  {{ item }}
                </a-radio>
                <a-input v-if="showCodeInput" style="width:180px;height: 30px;" v-model="codeInputValue" :maxLength="20" :disabled="!isEdit" />
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :md="12" :sm="24">

          </a-col> -->
        </a-row>

        <a-tabs v-model="currentTab" >
          <a-tab-pane v-if="$store.getters.project != null && pcVisible" key="1" tab="项目权限-PC端" >
            <a-row :gutter="48">
              <a-col :md="12" :sm="24">
                <a-form-model-item ref="ptsVisible" prop="ptsVisible" label="受试者可见">
                  <a-radio-group v-model="form.ptsVisible" @change="handleRadioChange" :disabled="!isEdit">
                    <a-radio :value="1"> 可见 </a-radio>
                    <a-radio :value="0"> 不可见 </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
            </a-row>
            <PermissionTable ref="pcTable" :is-edit="isEdit" :permission="permission" @check="checkedArr" />
          </a-tab-pane>
          <a-tab-pane v-if="$store.getters.project != null && miniVisible" key="3" tab="项目权限-小程序" >
            <PermissionTable ref="MPTable" :is-edit="isEdit" :permission="permissionMP" @check="checkedArrMP" />
          </a-tab-pane>
          <a-tab-pane v-if="$store.getters.project == null " key="4" tab="权限" >
            <a-row :gutter="48">
              <a-col :md="12" :sm="24">
                <a-form-model-item ref="ptsVisible" prop="ptsVisible" label="受试者可见">
                  <a-radio-group v-model="form.ptsVisible" @change="handleRadioChange" :disabled="!isEdit">
                    <a-radio :value="1"> 可见 </a-radio>
                    <a-radio :value="0"> 不可见 </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
            </a-row>
            <PermissionTable ref="Table" :is-edit="isEdit" :permission="permission" @check="checkedArr" />
          </a-tab-pane>
          <a-button v-if="(pcVisible || miniVisible || $store.getters.project == null) && isEdit" type="danger" ghost slot="tabBarExtraContent" @click="clearPermission" >
            清空列表
          </a-button>
        </a-tabs>
        <!-- <div v-if="$store.getters.project != null">
          <a-form-model-item v-show="pcVisible" ref="account" label="项目权限-PC端" >
            <a-tree
              v-model="checkedKeys"
              :replaceFields="replaceFields"
              checkable
              :tree-data="permission"
              @check="checkedArr"
              :checkStrictly="true"
            />
          </a-form-model-item>
          <a-form-model-item v-show="miniVisible" ref="account_mp" label="项目权限-小程序">
            <a-tree
              v-model="checkedKeysMP"
              :replaceFields="replaceFields"
              checkable
              :tree-data="permissionMP"
              @check="checkedArrMP"
              :checkStrictly="true"
            />
          </a-form-model-item>
        </div>
        <div v-else>
          <a-form-model-item ref="account" label="权限">
            <a-tree
              v-model="checkedKeys"
              :replaceFields="replaceFields"
              checkable
              :tree-data="permission"
              @check="checkedArr"
              :checkStrictly="true"
            />
          </a-form-model-item>
        </div> -->
      </a-form-model>
      <div class="drawer-btn" style="margin-top:20px">
        <center >
          <a-button :style="{ marginRight: '8px' }" @click="handleCancel"> 取消 </a-button>
          <a-button v-show="isEdit && btnVisible" type="primary" @click="onSubmit(false)"> 确定 </a-button>
        </center>
      </div>

      <!-- <div>{{ form }}</div> -->
      <ExitModal
        :visible="exitVisible"
        :saveLoading="saveLoading"
        @handleCancel="exitVisible = false"
        @savePage="savePage"
        @exitPage="exitPage"
      />
    </div>
  </page-header-wrapper>
</template>
<script>
import { upDataRole, upDataRoleByPro, getProjectUserRole, getSystemUserRole } from '@/api/system/role.js'
import PermissionTable from './components/components/permissionTable.vue'
import ExitModal from '@/components/exitModal/index.vue'
import _ from 'lodash'
export default {
  components: {
    PermissionTable,
    ExitModal
  },
  data () {
    return {
      currentTab: this.$store.getters.project != null ? '1' : '4',
      maskClosable: true,
      checkedKeys: this.rolePermission, // 树状keys
      checkedKeysMP: this.rolePermissionMP,
      autoExpandParent: true,
      roleCodeList: [],
      codeInputValue: '',
      showCodeInput: '',
      form: {
        id: '',
        name: '',
        // code: ['SYS_ADMIN', 'SYS_BIZ', 'CRC', 'PM', 'PI', '其他'].findIndex(item => item === this.$props.record.code) === -1 ? '其他' : this.$props.record.code,
        code: '',
        menuIds: '',
        ptsVisible: '',
        description: '',
        copyVisible: 0
      },
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id'
      },
      labelCol: {
        span: 4
      },
      wrapperCol: {
        span: 19
      },
      other: '',
      rules: {
        name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '名称长度限制在10个字以内',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入标识',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '标识长度限制在20个字以内',
            trigger: 'blur'
          }
        ],
        description: [
          {
            required: false,
            trigger: 'blur'
          },
          {
            min: 1,
            max: 100,
            message: '描述过长',
            trigger: 'blur'
          }
        ]
      },
      pcVisible: false,
      miniVisible: false,
      btnVisible: true,
      roleId: '',
      userRoleList: [],
      record: {},
      rolePermission: [],
      rolePermissionMP: [],
      permission: [],
      permissionMP: [],
      isEdit: false,
      isModify: false, // 是否修改了内容
      exitFn: null,
      exitVisible: false,
      saveLoading: false
    }
  },
  // vue 路由钩子
  beforeRouteLeave (to, from, next) {
    this.exitFn = next
    if (this.isModify && (this.isEdit && this.btnVisible)) {
      // this.$confirm({
      //   title: '提示',
      //   content: '您还没有保存配置内容，是否保存？',
      //   onOk () {
      //     // 调用保存
      //     that.onSubmit(true)
      //   }
      // })
      this.exitVisible = true
    } else {
      next()
    }
  },
  mounted () {
    const roles = localStorage.getItem('CURRENT_PERMISSION')
    if (roles) {
      const mData = JSON.parse(roles)
      this.permission = mData['permission']
      this.permissionMP = mData['permissionMP']
      this.rolePermission = mData['rolePermission']
      this.rolePermissionMP = mData['rolePermissionMP']
      this.isEdit = mData['isEdit']

      // this.checkedKeys = this.rolePermission // 树状keys
      // this.checkedKeysPad = this.rolePermissionPad
      // this.checkedKeysMP = this.rolePermissionMP
    }
    const currentRole = localStorage.getItem('CURRENT_ROLE')
    if (currentRole) {
      this.record = JSON.parse(currentRole)
    }
    if (this.record) {
      this.roleCodeList = this.$store.getters.project == null ? ['SYS_ADMIN', 'SYS_BIZ', 'SYS_FINANCE', '其他'] : ['CRC', 'PM', 'Investigator', 'Subjects', '其他']
      this.codeInputValue = (this.$store.getters.project == null ? ['SYS_ADMIN', 'SYS_BIZ', 'SYS_FINANCE', '其他'] : ['CRC', 'PM', 'Investigator', 'Subjects', '其他']).findIndex(item => item === this.record.code) === -1 ? this.record.code : ''
      this.showCodeInput = (this.$store.getters.project == null ? ['SYS_ADMIN', 'SYS_BIZ', 'SYS_FINANCE', '其他'] : ['CRC', 'PM', 'Investigator', 'Subjects', '其他']).findIndex(item => item === this.record.code) === -1

      this.form = {
        id: this.record.id,
        name: this.record.name,
        // code: ['SYS_ADMIN', 'SYS_BIZ', 'CRC', 'PM', 'PI', '其他'].findIndex(item => item === this.$props.record.code) === -1 ? '其他' : this.$props.record.code,
        code: (this.$store.getters.project == null ? ['SYS_ADMIN', 'SYS_BIZ', 'SYS_FINANCE', '其他'] : ['CRC', 'PM', 'Investigator', 'Subjects', '其他']).findIndex(item => item === this.record.code) === -1 ? '其他' : this.record.code,
        menuIds: this.record.menuIds,
        ptsVisible: this.record.ptsVisible,
        description: this.record.description,
        copyVisible: 0
      }

      this.$nextTick(() => {
        this.toggleShow(this.record.code)
        if (this.$store.getters.project != null) {
          if (this.miniVisible) {
            this.currentTab = '3'
          }

          if (this.pcVisible) {
            this.currentTab = '1'
          }
        } else {
          this.currentTab = '4'
        }
        if (this.permission && this.rolePermission) {
          this.form.menuIds = JSON.parse(JSON.stringify(this.rolePermission))
          this.setPmsParams(this.permission, this.rolePermission)
          console.log(this.rolePermission, '当前对象', this.permission)
          this.$nextTick(() => {
            if (this.$refs.pcTable !== undefined) {
              this.$refs.pcTable.updataView()
            }
            if (this.$refs.Table !== undefined) {
              this.$refs.Table.updataView()
            }
          }, 500)
        }
        if (this.permissionMP && this.rolePermissionMP) {
          this.form.menuIdsMP = JSON.parse(JSON.stringify(this.rolePermissionMP))
          this.setPmsParams(this.permissionMP, this.rolePermissionMP)
          this.$nextTick(() => {
            if (this.$refs.MPTable !== undefined) {
              this.$refs.MPTable.updataView()
            }
          }, 500)
        }
        this.$forceUpdate()
      })
    }
    if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL)
      window.addEventListener('popstate', this.onCloseModal, false)
    }
  },
  destroyed () {
    window.removeEventListener('popstate', this.onCloseModal, false)
  },
  methods: {
    onCloseModal () {
      history.pushState(null, null, document.URL)
      this.$router.push({ name: 'system' })
    },
    // 退出页面
    exitPage () {
      this.exitVisible = false
      this.exitFn()
    },
    // 保存页面
    savePage () {
      this.saveLoading = true
      this.onSubmit(true)
    },
    handleCopyChange (e) {
      if (e.target.value === 1) {
        this.getUserRoleList()
      }
    },
    handleNameChange () {
      this.getUserRoleList()
    },
    handleDesChange () {
      this.isModify = true
    },
    handleRadioChange () {
      this.isModify = true
    },
    getUserRoleList () {
      if (this.$store.getters.project != null) {
        getProjectUserRole({ name: this.form.name, proId: this.$store.getters.project.id }).then(res => {
          this.userRoleList = res
        })
      } else {
        getSystemUserRole({ name: this.form.name }).then(res => {
          this.userRoleList = res
        })
      }
    },
    onSubmit (flag = false) {
      // console.log(this.rolePermission)
      // this.$refs.ruleForm.validate(valid => {
      //   if (valid) {
      //     this.form.menuIds = this.rolePermission.filter(n => n).toString()
      //     console.log(this.form)
      //     // this.form.menuIds = JSON.stringify(this.form.menuIds)
      //     upDataRole(this.form)
      //       .then(res => {
      //         this.buttonLoading = false
      //         this.$message.success('修改成功')
      //         // this.handleCancel()
      //         this.$parent.$refs.table.refresh(true)
      //       })
      //       .catch(() => {
      //         this.buttonLoading = false
      //       })
      //   } else {
      //     this.buttonLoading = false
      //     console.log('error submit!!')
      //     return false
      //   }
      // })

      // console.log(this.rolePermission)
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log('=========', this.checkedKeysMP, this.checkedKeys)
          // debugger
          // this.form.menuIds = this.checkedKeys.checked != null ? this.checkedKeys.checked.filter(n => n).toString() : this.checkedKeys.filter(n => n).toString()
          // this.form.menuIdsMP = this.checkedKeysMP.checked != null ? this.checkedKeysMP.checked.filter(n => n).toString() : this.checkedKeysMP.filter(n => n).toString()
          console.log(this.form)
          if (this.$store.getters.project != null) {
            // 提交的 menuIdsMP 字段 请忽略
            const menuIds = []
            if (this.form.menuIds && this.form.menuIds.length) {
              menuIds.push(...this.form.menuIds)
            }
            if (this.form.menuIdsMP && this.form.menuIdsMP.length) {
              menuIds.push(...this.form.menuIdsMP)
            }
            if (menuIds.length === 0) {
              this.$message.warning('请选择权限')
              return
            }
            upDataRoleByPro({
              ...this.form,
              code: this.showCodeInput ? this.codeInputValue : this.form.code,
              menuIds: _.uniq(menuIds).join(','),
              systemId: this.$const.SYSTEM_TYPE.PAYMENT.value,
              proId: this.$store.getters.project.id
              // proId: 30063
            }).then(res => {
            this.buttonLoading = false
            this.$message.success('编辑成功')
            this.isModify = false
            if (flag === true) {
              this.exitFn()
            } else {
              this.handleCancel()
            }
          })
          } else {
            if (this.form.menuIds.length === 0) {
              this.$message.warning('请选择权限')
              return
            }
            upDataRole({
              ...this.form,
              code: this.showCodeInput ? this.codeInputValue : this.form.code,
              menuIds: _.uniq(this.form.menuIds).join(','),
              systemId: this.$const.SYSTEM_TYPE.PAYMENT.value
            }).then(res => {
              this.buttonLoading = false
              this.$message.success('编辑成功')
              this.isModify = false
              if (flag === true) {
                this.exitFn()
              } else {
                this.handleCancel()
              }
            })
          }
        } else {
          this.buttonLoading = false
          console.log('error submit!!')
          return false
        }
      })
    },
    checkedArr (checkedKeys) {
      // console.log(checkedKeys)
      // this.rolePermission = checkedKeys.checked.filter(n => n).toString()
      this.form.menuIds = checkedKeys
      this.isModify = true
    },
    checkedArrMP (checkedKeys) {
      // console.log(checkedKeys.checked.toString())
      this.form.menuIdsMP = checkedKeys
      this.isModify = true
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
    },
    // 选择集合
    collectRow (Rows) {
      this.selectedGroud = Rows
    },
    // 处理取消
    handleCancel () {
      this.$router.go(-1)
    },
    handleCodeChange (e) {
      console.log('=======', e)
      if (e.target.value === '其他') {
        this.showCodeInput = true
      } else {
        this.showCodeInput = false
      }
    },
    toggleShow (val) {
      console.log(val, '*********val**********')
      this.pcVisible = true
      this.miniVisible = true
      this.btnVisible = true
      if (val === 'PM' || val === 'CRC') {
        this.miniVisible = false
      } else if (val === 'Investigator') {
        this.pcVisible = false
      } else if (val === 'Subjects') {
        this.pcVisible = false
        this.btnVisible = false
      } else {
        this.miniVisible = false
      }
      if (val === 'PROJECT_ADMIN') {
        this.pcVisible = true
        this.miniVisible = true
        this.btnVisible = false
      }
    },
    // 清空权限
    clearPermission () {
      this.isModify = true
      if (this.currentTab === '1') {
        this.setPmsParams(this.permission)
        this.form.menuIds = []
        this.$refs.pcTable.clearAll()
      }
      if (this.currentTab === '3') {
        this.setPmsParams(this.permissionMP, [])
        this.form.menuIdsMP = []
        this.$refs.MPTable.clearAll()
      }
      if (this.currentTab === '4') {
        this.setPmsParams(this.permissionMP, [])
        this.form.menuIds = []
        this.$refs.Table.clearAll()
      }
      this.$forceUpdate()
    },
    // 遍历加参数字段
    setPmsParams (permission, rolePermission) {
      if (permission && permission.length) {
        permission.forEach(item => {
          if (rolePermission && rolePermission.indexOf(item.id) >= 0) {
            item.checked = true
          } else {
            item.checked = false
          }

          if (item.child && item.child.length) {
            item.child.forEach(item1 => {
              if (rolePermission && rolePermission.indexOf(item1.id) >= 0) {
                item1.checked = true
              } else {
                item1.checked = false
              }
            })
          }
          if (item.children) {
            this.setPmsParams(item.children, rolePermission)
          }
        })
      }
    },
    // 处理用户权限
    handleUserRoleChange () {
      if (this.userRoleList && this.userRoleList.length) {
        const data = this.userRoleList.find(item => {
          return item.roleId === this.roleId
        })
        if (data) {
          if (data.pms) {
            const rolePermission = data.pms.split(',').map(Number)
            this.form.menuIds = rolePermission
            this.setCheckedParams(this.permission, rolePermission)
            this.$nextTick(() => {
              if (this.$refs.pcTable !== undefined) {
                this.$refs.pcTable.updataView()
              }
              if (this.$refs.Table !== undefined) {
                this.$refs.Table.updataView()
              }
            }, 500)
          }
          if (data.mini) {
            const rolePermission = data.mini.split(',').map(Number)
            this.form.menuIdsMP = rolePermission
            this.setCheckedParams(this.permissionMP, rolePermission)
            this.$nextTick(() => {
              if (this.$refs.MPTable !== undefined) {
                this.$refs.MPTable.updataView()
              }
            }, 500)
          }
          this.form.ptsVisible = data.ptsVisible ? 1 : 0
        }
      }
    },
    // 遍历加参数字段
    setCheckedParams (permission, rolePermission) {
      if (permission && permission.length) {
        permission.forEach(item => {
          if (rolePermission && rolePermission.indexOf(item.id) >= 0) {
            item.checked = true
          } else {
            item.checked = false
          }

          if (item.child && item.child.length) {
            item.child.forEach(item1 => {
              if (rolePermission && rolePermission.indexOf(item1.id) >= 0) {
                item1.checked = true
              } else {
                item1.checked = false
              }
            })
          }
          if (item.children) {
            this.setCheckedParams(item.children, rolePermission)
          }
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
  .permissionContent{
    background:white;
    margin: 0 auto;
    padding: 20px;
  }

</style>
